package com.zyzo.demo.appengine.model;

import java.util.ArrayList;
import java.util.List;

import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.googlecode.objectify.util.DAOBase;

public class ItemDao  extends DAOBase 
{
	private static ItemDao _instance=null ;
	protected ItemDao()
	{
		ObjectifyService.register(Item.class);
	}
	public static ItemDao getInstance()
	{
		if(null==ItemDao._instance)ItemDao._instance = new ItemDao();
		return ItemDao._instance;
	}

	
	    public List<Item> getAllItem( )
	    {
	    	ArrayList<Item> items = new ArrayList<Item>();
	    		
	    	Query<Item> q  = ofy().query( Item.class );	    	
	    	for (Item u : q) items.add(u);
	    	
	    	return items;
	    }
	    
	    public Item getItem( long id )
	    {
	    	Item found = ofy().find( Item.class, id );
	    	return found;
	    }
    
 	    public void updateItem(Item o)  throws Exception
	    {
 	    	Item found = ofy().find( Item.class, o.getId() );
	        if (found != null)
	        {
	        	ofy().delete( found );
	        	ofy().put( o );
	        }
	        else
		    {
		      	throw new Exception("No item  with id "+o.getId()+" already exists.");
		    }
	        return  ;
	    }
	    
		public void createItem(Item o) throws Exception
		{
			Item found = ofy().find( Item.class, o.getId() );
	        if (found == null)
	        {	        	
	        	ofy().put( o );
	        }
	        else
	        {
	        	throw new Exception("a item with id "+o.getId()+" already exists.");
	        }
	        return  ;
		}
}
